package com.zxisl.service;

import com.zxisl.utils.ESUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Service;

/**
 * Created by ade on 2016/10/18.
 */
@Service
public class WeiboService {

    //TODO 写这里必须项目启动后把若干个es的客户端链接放置到连接池中，目前还没有写
    /**
     *  查询数据，支持分词
     * @param content 要查询的文档内容
     * @param filedName 字段名称
     * @param indexName  索引名称
     * @param typeName  类型名
     * @param num   要展示的数据的数量
     */
    public static void queryStringQuery(String content,String filedName ,String indexName,String typeName,int num) {
        System.out.println("queryStringQuery......");
        TransportClient client = ESUtils.getTransportClient();

        QueryBuilder qb = QueryBuilders.boolQuery()
                .must(QueryBuilders.queryStringQuery(content).defaultField(filedName));

        SearchResponse res = client.prepareSearch(indexName)
                .setTypes(typeName)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(qb)
                .setFrom(0)
                .setSize(num)
                .execute().actionGet();
        for (SearchHit hit: res.getHits().getHits()){
            System.out.println(hit.getSourceAsString());
        }
        //TODO 这里数据返回到页面即可
        //TODO 客户端链接回收
        client.close();
    }

    /**
     * 查询数据，支持分数的升降，数据权重分配
     * @param proContent
     * @param proFiledName
     * @param negContent
     * @param negFiledName
     * @param indexName
     * @param typeName
     * @param boostNum
     * @param num
     */
    public static void boostQuery(String proContent,String proFiledName ,String negContent,String negFiledName,String indexName,String typeName,float boostNum,int num) {
        System.out.println("boostQuery......");
        TransportClient client = ESUtils.getTransportClient();
        QueryBuilder qb = QueryBuilders.boostingQuery()
                .positive(QueryBuilders.queryStringQuery(proContent).defaultField(proFiledName))
                .negative(QueryBuilders.termQuery(negFiledName,negContent))
                .negativeBoost(boostNum);

        SearchResponse res = client.prepareSearch(indexName)
                .setTypes(typeName)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(qb)
                .setFrom(0)
                .setSize(num)
                .execute().actionGet();
        for (SearchHit hit: res.getHits().getHits()){
            System.out.println(hit.getSourceAsString());
        }
        client.close();
    }
}
